package com.baichen;

import java.lang.reflect.Field;

/**
 * Before通知处理器
 * 在目标方法执行前执行指定的逻辑
 */
public class BeforeHandler implements MyHandler {
    
    private MyInterface target;
    private String beforeLogic;
    
    /**
     * 构造函数
     * @param target 目标对象
     * @param beforeLogic 在方法执行前要执行的逻辑代码
     */
    public BeforeHandler(MyInterface target, String beforeLogic) {
        this.target = target;
        this.beforeLogic = beforeLogic;
    }
    
    /**
     * 构造函数 - 使用默认的before逻辑
     * @param target 目标对象
     */
    public BeforeHandler(MyInterface target) {
        this(target, "System.out.println(\"Before advice: 方法即将执行\");");
    }
    
    @Override
    public String functionBody(String methodName) {
        StringBuilder sb = new StringBuilder();
        // 添加before逻辑
        sb.append(beforeLogic).append("\n");
        // 调用目标方法
        sb.append("target.").append(methodName).append("();\n");
        return sb.toString();
    }
    
    @Override
    public void setMyInterface(MyInterface myInterfaceObject) throws NoSuchFieldException, IllegalAccessException {
        // 获取生成的代理类的Class对象
        Class<? extends MyInterface> aClass = myInterfaceObject.getClass();
        
        // 设置target字段
        Field targetField = aClass.getDeclaredField("target");
        targetField.setAccessible(true);
        targetField.set(myInterfaceObject, target);
    }
} 